var B = {
    cache : {},
    unread : {
        length : 0,
        data : {}
    }
};

$(document).ready(function() {
    B.times();
});

B.msg = function(title, body, obj) {
    if (window.webkitNotifications
            && window.webkitNotifications.createNotification) {

        var icon = "icon.png";
        var msgObj = window.webkitNotifications.createNotification(icon, title,
                body);
        msgObj.show();
        msgObj.onclose = function() {
            B.close(obj);
        };
    }
};

B.close = function(obj) {
    B.unread.remove(obj)
    B.setCount();
    var url = U.basepath + "/closeTimingTasks.do";
    $.get(url, {
        'id' : obj
    });
};

B.checkMsg = function() {
    try{
        B.init();
    }catch(e){
    }
    setTimeout(B.checkMsg, 1000 * 60);
};

B.times = function() {
    setTimeout(B.checkMsg, 1000);
};

B.init = function() {
    var url = U.basepath + "/queryTimingTasks.do";
    $.post(url, function(data) {
        for ( var i in data) {
            var _date = new Date(data[i].date.time);
            B.msg(_date.format("yyyy-MM-dd hh:mm"), data[i].text, data[i].id);
            B.unread.add(data[i].id);
            B.setCount();
        }
    });

};

B.setCount = function() {
    chrome.browserAction.setBadgeText({
        text : B.unread.length == 0 ? "" : B.unread.length + ""
    });
};

B.unread.add = function(obj) {
    B.unread.data[obj] = "1";
    B.unread.length++;
};

B.unread.remove = function(obj) {
    if (B.unread.data[obj]) {
        delete B.unread.data[obj];
        B.unread.length--;
    }
};